package cn.sciento.farm.devicemanager.api.jsonrpc.impl;

import cn.sciento.farm.devicemanager.api.jsonrpc.CameraJsonApi;
import cn.sciento.farm.devicemanager.common.constant.DeviceImgConstant;
import cn.sciento.farm.devicemanager.common.constant.ResultConstant;
import cn.sciento.farm.devicemanager.common.util.ReturnUtil;
import cn.sciento.farm.devicemanager.common.util.qiniu.QiniuResult;
import cn.sciento.farm.devicemanager.common.util.qiniu.QiniuUploadUtil;
import cn.sciento.farm.devicemanager.common.util.qiniu.ResultCode;
import cn.sciento.farm.devicemanager.dao.entity.DevCamera;
import cn.sciento.farm.devicemanager.dao.model.ResponseMessage;
import cn.sciento.farm.devicemanager.sensor.Error;
import cn.sciento.farm.devicemanager.sensor.*;
import cn.sciento.farm.devicemanager.service.CameraService;
import cn.sciento.fluorite.response.WebLiveAddress;
import com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImpl;
import com.mchange.v1.util.CollectionUtils;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import static cn.sciento.farm.devicemanager.common.util.ReturnUtil.getReturnMap;


@Service
@AutoJsonRpcServiceImpl
public class CameraJsonApiImpl implements CameraJsonApi {

    @Autowired
    private CameraService cameraService;




    @Override
    public ResponseMessage create(DevCamera camera, String validateCode) {
        if (camera.getChannelNo() <= 0
                || StringUtils.isEmpty(camera.getDeviceSerial())
                || StringUtils.isEmpty(camera.getName())
                || StringUtils.isEmpty(camera.getLocation())
                || StringUtils.isEmpty(validateCode)
                || camera.getAreaId() <= 0
        ) {
            return getReturnMap(ResultConstant.NULL_PARAMETER);
        } else {
            if (camera.getLocation().split(",").length != 2) {
                return getReturnMap(ResultConstant.INVALID_LENGTH);
            }
            DevCamera oldCamera = cameraService.getBySerial(camera.getDeviceSerial(), camera.getChannelNo());
            if (oldCamera != null) {
                return getReturnMap(ResultConstant.REPEAT_PARAMETER);
            } else {
                camera.setCoverImage(uploadImage(camera.getCoverImage()));
                camera.setCreateTime(System.currentTimeMillis());
                camera.setUpdateTime(System.currentTimeMillis());
                int count = 0;
                try {
                    count = cameraService.insert(camera, validateCode);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return getReturnMap(ResultConstant.SUCCESS,count,camera);

            }


        }
    }

    @Override
    public ResponseMessage update(DevCamera camera) {
        if (camera.getId() <= 0) {
            return getReturnMap(ResultConstant.INVALID_PARAMETER);
        } else {
            DevCamera devCamera = new DevCamera();
            devCamera.setId(camera.getId());
            devCamera.setName(camera.getName());
            if (StringUtils.isNotEmpty(camera.getCoverImage())) {
                devCamera.setCoverImage(camera.getCoverImage());
            }
            devCamera.setCoverImage(uploadImage(camera.getCoverImage()));
            devCamera.setLocation(camera.getLocation());
            devCamera.setUpdateTime(System.currentTimeMillis());
            devCamera.setRemark(camera.getRemark());
            devCamera.setDeviceType(camera.getDeviceType());
            int count = cameraService.updateById(devCamera);
            return getReturnMap(ResultConstant.SUCCESS,count,devCamera.getId());
        }
    }

    private String uploadImage(String data){
        if(StringUtils.isEmpty(data)){
            return data;
        }
        if(data.startsWith("http://picture.visfarm.com")){
            return data;
        }else {
            String key = String.format(DeviceImgConstant.SIMPLE_TEMPLATE, DeviceImgConstant.TYPE_CAMERA,
                    UUID.randomUUID().toString().replace("-", "") + ".jpg");

            QiniuResult qiniuResult = QiniuUploadUtil.uploadRewrite(Base64.getDecoder().decode(data), key);
            if (qiniuResult == null) {
                return null;
            }
            if (qiniuResult.getCode() == ResultCode.SUCCESS) {
                return qiniuResult.getUrl();
            }
        }
        return null;
    }

    @Override
    public ResponseMessage get(Long id) {
        DevCamera devCamera = cameraService.getById(id);
        return getReturnMap(ResultConstant.SUCCESS,devCamera);

    }

    @Override
    public ResponseMessage list(Integer areaId) {
        List<DevCamera> cameraList = cameraService.getByAreaId(areaId);

        return getReturnMap(ResultConstant.SUCCESS,cameraList);

    }

    @Override
    public ResponseMessage delete(Long id) {
        int count = cameraService.deleteById(id);
        return getReturnMap(ResultConstant.SUCCESS,count);

    }

    @Override
    public ResponseMessage getLive(Long id) {
        WebLiveAddress webLiveAddress = cameraService.getLiveById(id);
        return getReturnMap(ResultConstant.SUCCESS,webLiveAddress);
    }

    @Override
    public ResponseMessage controlPTZ(Long id ,int direction,int speed) {
        int count = cameraService.controlPTZ(id, direction,speed);
        return getReturnMap(ResultConstant.SUCCESS,count);

    }

    @Override
    public ResponseMessage getMultiLive(String ids) {
        List<WebLiveAddress> liveList = Arrays.asList(ids.split(",")).stream().map((String id)->{
            return cameraService.getLiveById(Long.parseLong(id));
        }).collect(Collectors.toList());
        return getReturnMap(ResultConstant.SUCCESS,liveList);
    }
}
